package com.yuezhu.versionup;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 
 * 线程池管理类,获取消费队列信息,开始下载任务
 * 
 * 
 */
public class ThreadPoolManager {

	private static final String TAG = "ThreadPoolManager";

	/** 线程池的大小 */
	private int poolSize;
	private static final int MIN_POOL_SIZE = 1;
	private static final int MAX_POOL_SIZE = 10;

	/** 线程池 */
	private ExecutorService threadPool;

	/** 消费线程获取队列内容 */
	private Thread poolThread;

	/** 轮询时间 */
	private static final int SLEEP_TIME = 200;

	/** 存储当前已经启动的线程 **/
	private Map<String, ArrayList<DownloadTask>> threadDownList = new ConcurrentHashMap<String, ArrayList<DownloadTask>>();
	/** 用于统计已经完成线程 **/
	private Map<String, ArrayList<String>> finishThreadDownList = new ConcurrentHashMap<String, ArrayList<String>>();
	private Map<String, Handler> finishThreadDownListHandler = new ConcurrentHashMap<String, Handler>();

	public ThreadPoolManager(int poolSize) {
		if (poolSize < MIN_POOL_SIZE)
			poolSize = MIN_POOL_SIZE;
		if (poolSize > MAX_POOL_SIZE)
			poolSize = MAX_POOL_SIZE;
		this.poolSize = poolSize;

		threadPool = Executors.newFixedThreadPool(this.poolSize);
	}

	/**
	 * 开启线程池轮询
	 * 
	 * @return
	 */
	public void start() {
		if (poolThread == null) {
			poolThread = new Thread(new PoolRunnable());
			poolThread.start();
			// 启动完成线程
			new Thread(new FinishRunnable()).start();
		}
	}

	/**
	 * 结束轮询，关闭线程池
	 */
	public void stop() {
		poolThread.interrupt();
		poolThread = null;
	}

	/**
	 * 暂停线程
	 * 
	 * @param downUrl
	 */
	public void pauseTask(String taskId) {
		// 获取到所有此任务的线程
		ArrayList<DownloadTask> downTasks = threadDownList.get(taskId);
		if (null != downTasks) {
			for (DownloadTask downloadTask : downTasks) {
				downloadTask.setState(DownloadState.PAUSE);
			}
		}
	}

	/**
	 * 实现消费线程
	 */
	private class PoolRunnable implements Runnable {

		@Override
		public void run() {
			Log.i(TAG, "开始轮询");

			while (true) {
				try {
					// 获取任务队列
					TaskQueue queue = TaskQueue.getInst();
					int size = queue.size();

					if (size > 0) {

						System.out.println("liu game get task=" + size);

						// 启动任务，加入线程池
						DownloadInfo downInfo = queue.getMessage(2000);
						if (null != downInfo) {
							System.gc();
							// String downUrl = downInfo.getDownUrl();
							String taskId = downInfo.getTaskId();
							// 判断当前下载地址是否已经启动线程,启动了,则不重复添加任务
							// if(!threadDownList.containsKey(downUrl)){
							System.out.println(taskId
									+ " liu game threadDownlist="
									+ threadDownList);
							if (!threadDownList.containsKey(taskId)) {
								Handler myHandler = downInfo.getMsgHandler();
								Context myContext = downInfo.getMyContext();
								// 启动的所有子线程
								ArrayList<DownloadTask> threads = new ArrayList<DownloadTask>();
								ArrayList<String> finishThreads = new ArrayList<String>();

								List<DownloadInfoTask> childs = downInfo
										.getChildDownInfos();
								if (null != childs && childs.size() > 0) {
									for (DownloadInfoTask childDownLoadInfo : childs) {
										String uuid = UUID.randomUUID()
												.toString();
										DownloadTask threadTask = new DownloadTask(
												myContext, childDownLoadInfo,
												myHandler, uuid);
										threads.add(threadTask);
										threadPool.execute(threadTask);
										ActivityTaskQueue.getInst().addMessage(
												uuid);
										finishThreads.add(uuid);
									}
								}
								// threadDownList.put(downUrl, threads);
								// finishThreadDownList.put(downUrl,
								// finishThreads);
								// finishThreadDownListHandler.put(downUrl,
								// myHandler);
								threadDownList.put(taskId, threads);
								finishThreadDownList.put(taskId, finishThreads);
								finishThreadDownListHandler.put(taskId,
										myHandler);
								// 通知开始启动
								Message message = Message.obtain();
								message.what = DownloadState.INIT;
								// message.obj = downUrl;
								message.obj = taskId;
								message.arg1 = downInfo.getCompeleteSize();
								message.arg2 = downInfo.getFileSize();
								myHandler.sendMessage(message);

								System.out.println("liu game start task");
							}
						}
					} else {
						Thread.sleep(SLEEP_TIME);
					}
				} catch (InterruptedException e) {
					Log.e(TAG, e.getMessage() + "");
				}
			}
		}
	}

	/**
	 * 处理完成线程
	 * 
	 * @author zuo
	 */
	private class FinishRunnable implements Runnable {

		@SuppressWarnings({ "rawtypes", "unchecked" })
		@Override
		public void run() {
			while (true) {
				try {
					System.out.println("liu game download finishRunnable");

					Thread.sleep(1000);
					if (finishThreadDownList.size() == 0) {
						continue;
					}
					System.gc();
					Iterator itr = finishThreadDownList.entrySet().iterator();
					// 未完成的
					Map<String, ArrayList<String>> noFinishThreadDownList = new ConcurrentHashMap<String, ArrayList<String>>();
					// 已完成的
					Set<String> finishUrl = new HashSet<String>();
					while (itr.hasNext()) {
						Map.Entry<String, ArrayList<String>> cb = (Map.Entry<String, ArrayList<String>>) itr
								.next();
						System.out
								.println("liu game download finishRunnable cb="
										+ cb);
						if (null != cb) {
							// String downUrl = cb.getKey();
							String taskId = cb.getKey();
							System.out
									.println("liu game download finishRunnable cb.key="
											+ taskId);
							ArrayList<String> uuids = cb.getValue();
							ArrayList<String> exist = new ArrayList<String>();
							if (null != uuids && uuids.size() > 0) {
								for (String uuid : uuids) {
									if (ActivityTaskQueue.getInst().existUUID(
											uuid)) {
										exist.add(uuid);
									}
								}
							}
							System.out
									.println("liu game download finishRunnable cb exist.size="
											+ exist.size());
							if (exist.size() > 0) {
								// noFinishThreadDownList.put(downUrl, exist);
								noFinishThreadDownList.put(taskId, exist);
							} else {
								// finishUrl.add(downUrl);
								System.out
										.println("liu game download finishRunnable cb finishUrl.add="
												+ taskId);
								finishUrl.add(taskId);
							}
						}
					}
					// 处理未完成的
					finishThreadDownList = noFinishThreadDownList;
					// 处理已经完成的任务
					System.out
							.println("liu game download finishRunnable cb size="
									+ finishUrl.size());
					if (finishUrl.size() > 0) {
						for (String taskId : finishUrl) {

							System.out
									.println("liu game download finishRunnable cb finish taskId="
											+ taskId);

							// 完成
							Handler myHandler = finishThreadDownListHandler
									.get(taskId);

							ArrayList<DownloadTask> tasks = threadDownList
									.get(taskId);
							Context mContext = null;
							if (null != tasks) {
								mContext = tasks.get(0).getmContext();
							}

							System.out
									.println("liu game download finishRunnable cb finish mContext="
											+ mContext);

							finishThreadDownList.remove(taskId);
							threadDownList.remove(taskId);

							if (null != mContext) {
								if (SQLiteDownDatabase.getInstance(mContext)
										.finishTask(taskId)) {
									// 通知前台
									Message message = Message.obtain();
									message.what = DownloadState.FINISH;
									message.obj = taskId;
									myHandler.sendMessage(message);

									System.out
											.println("liu game download finishRunnable cb finish true");

									// 删除已经完成的数据库记录
									SQLiteDownDatabase.getInstance(mContext)
											.delete(taskId);
								}
							}
						}
					}
					System.gc();
				} catch (Exception e) {
					Log.d("判断完成任务线程异常", e.getMessage());
				}
			}
		}
	}
}